package com.codemeta.bokit.security.exception;

import cn.dev33.satoken.exception.DisableLoginException;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.dev33.satoken.exception.SaTokenException;
import com.codemeta.bokit.comm.global.DefaultErrorCode;
import com.codemeta.bokit.comm.global.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 安全组件_全局异常增强器
 *
 * @author hice
 */
@Slf4j
@Order(SecurityExceptionHandler.ORDER_VALUE)
@ControllerAdvice
public class SecurityExceptionHandler {

    public static final int ORDER_VALUE = -100;

    /**
     * sa-token全局异常拦截（拦截组件中的所有异常）
     *
     * @param ex .
     * @return .
     */
    @ResponseBody
    @ExceptionHandler
    public ResponseResult<String> saTokenException(SaTokenException ex) {
        // 不同异常返回不同状态码
        ResponseResult<String> result;
        if (ex instanceof NotLoginException) {
            // 如果是未登录异常
            NotLoginException ee = (NotLoginException) ex;
            result = ResponseResult.fail(DefaultErrorCode.unauthorized, ee.getMessage());
        } else if (ex instanceof NotRoleException) {
            // 如果是角色异常
            NotRoleException ee = (NotRoleException) ex;
            result = ResponseResult.fail(DefaultErrorCode.unauthorized, "无此角色：" + ee.getRole());
        } else if (ex instanceof NotPermissionException) {
            // 如果是权限异常
            NotPermissionException ee = (NotPermissionException) ex;
            result = ResponseResult.fail(DefaultErrorCode.unauthorized, "无此权限：" + ee.getCode());
        } else if (ex instanceof DisableLoginException) {
            // 如果是被封禁异常
            DisableLoginException ee = (DisableLoginException) ex;
            result = ResponseResult.fail(DefaultErrorCode.unauthorized, "账号被封禁：" + ee.getDisableTime() + "秒后解封");
        } else {
            // 普通异常, 输出：500 + 异常信息
            result = ResponseResult.fail(DefaultErrorCode.SERVER_INTERNAL, ex.getMessage());
        }
        // 返回给前端
        return result;
    }

}